package com.xunk.scene.util;

import cn.hutool.extra.validation.BeanValidationResult;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.scene.util
 * @ClassName: ValidationUtils
 * @Author: luanzhiwei
 * @Description: 校验工具类
 * @Date: 2021/5/19 16:53
 * @Version: 1.0
 */
public class ValidationUtils {
    /**
     * 默认{@link Validator} 对象
     */
    private static final Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 获取原生{@link Validator} 对象
     *
     * @return {@link Validator} 对象
     */
    public static Validator getValidator() {
        return validator;
    }

    /**
     * 校验对象
     *
     * @param <T>    Bean类型
     * @param bean   bean
     * @param groups 校验组
     * @return {@link Set}
     */
    public static <T> void validate(T bean, Class<?>... groups) {
        final Set<ConstraintViolation<T>> constraintViolations = validator.validate(bean, groups);
        if (constraintViolations.size() > 0) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }

    /**
     * 校验bean的某一个属性
     *
     * @param <T>          Bean类型
     * @param bean         bean
     * @param propertyName 属性名称
     * @param groups       验证分组
     * @return {@link Set}
     */
    public static <T> void validateProperty(T bean, String propertyName, Class<?>... groups) {
        final Set<ConstraintViolation<T>> constraintViolations = validator.validateProperty(bean, propertyName, groups);
        if (constraintViolations.size() > 0) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }


}
